package com.huaxin.hxmodulerabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.RetryInterceptorBuilder;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.interceptor.RetryOperationsInterceptor;

import java.util.Collections;

@Configuration
public class RabbitConfig {

    // ====== 队列、交换机、路由键定义 ======
    public static final String MESSAGE_QUEUE = "app.notification.queue";
    public static final String EXCHANGE = "app.message.exchange";

    // 🌟 使用通配符前缀，而不是固定值
    public static final String ROUTING_KEY_PATTERN = "notification.*";

    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(RabbitConfig.class);

    @Bean
    public Queue notificationQueue() {
        return QueueBuilder.durable(MESSAGE_QUEUE).build();
    }

    @Bean
    public TopicExchange exchange() {
        return new TopicExchange(EXCHANGE);
    }

    // ✅ 修改 Binding：使用通配符匹配所有 notification.xxx
    @Bean
    public Binding binding(Queue notificationQueue, TopicExchange exchange) {
        return BindingBuilder.bind(notificationQueue)
                .to(exchange)
                .with(ROUTING_KEY_PATTERN); // 👈 使用 notification.*
    }

    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    // ====================== 重试机制 ======================
    @Bean
    public RetryOperationsInterceptor rabbitRetryInterceptor() {
        return RetryInterceptorBuilder.stateless()
                .maxAttempts(3)
                .backOffOptions(1000, 2.0, 10000)
                .recoverer((message, exception) -> {
                    log.error("💥 消息消费最终失败，进入死信或告警！Body: {}", new String(message.getBody()), exception);
                })
                .build();
    }

    // ====================== 容器工厂 ======================
    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(
            ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(jsonMessageConverter());
        factory.setConcurrentConsumers(1);
        factory.setMaxConcurrentConsumers(5);
        factory.setAdviceChain(rabbitRetryInterceptor());
        factory.setAcknowledgeMode(AcknowledgeMode.AUTO);
        return factory;
    }
}